package com.qys.livesMall.product.entity;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, Arrays.toString(parameter));
    }

    @Override
    public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseArray(rs.getString(columnName));
    }

    @Override
    public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseArray(rs.getString(columnIndex));
    }

    @Override
    public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseArray(cs.getString(columnIndex));
    }

    private String[] parseArray(String columnValue) {
        if (columnValue == null) {
            return null;
        }
        // 解析字符串，去掉首尾的括号并按逗号分隔成数组
        String[] array = columnValue.substring(1, columnValue.length() - 1).split(", ");
        // 去除每个元素两侧的引号
        for (int i = 0; i < array.length; i++) {
            array[i] = array[i].substring(1, array[i].length() - 1);
        }
        return array;
    }
}
